package com.tanger.auth.auth;

import cn.hutool.core.bean.BeanUtil;
import com.tanger.auth.mapper.AuthMapper;
import com.tanger.common.redis.RedisUtil;
import com.tanger.common.vo.UserDetail;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/***
 *   封装 /auth/token的返回内容格式
 * */
@Component
@Aspect
public class AuthTokenAspect {
    @Autowired
    private RedisUtil redisUtil;
//    @Autowired
//    private UserPermissionMapper userPermissionMapper;
    @Autowired
    private AuthMapper authMapper;
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /// @Around是可以改变controller返回值的
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        //服务直接调用不需要转换格式
        Object[] args = pjp.getArgs();//2.传参  
        Map<String,Object> param = (Map<String,Object>)args[1];
        if(!param.containsKey("client_id")){
            return pjp.proceed();
        }
        String mobile = param.get("username").toString();
        // 放行
        Response response = new Response();
        try{
            Object proceed = pjp.proceed();
            if (proceed != null) {
                ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
                OAuth2AccessToken body = responseEntity.getBody();
                if (responseEntity.getStatusCode().is2xxSuccessful()) {
                    response.setErrorcode(HttpServletResponse.SC_OK+"");
                    response.setValue("Operation is Successful");
                    response.setData(body);
                    UserDetail user = authMapper.queryUserInfoByPhone(mobile);
                    // TODO 用户操作权限查询
//                    List<LinkedHashMap<String,Object>> permissionList = userPermissionMapper.queryUserPermissionList(user.getId());
//                    Map<String, Object> map = BeanUtil.beanToMap(user);
//                    map.put("permissions",permissionList);
//                    map.put("id",user.getId().toString());
                    response.setResultMap(BeanUtil.beanToMap(user));
                    //缓存用户对象
//                    boolean isExist1 = redisUtil.hasKey(RedisConstants.BASE_TOKEN_PREFIX+body.getValue());
//                    if (!isExist1) {
//                        redisUtil.set(RedisConstants.BASE_TOKEN_PREFIX+body.getValue(),user, body.getExpiresIn());
//                    }
                } else {
                    logger.error("error:{}", responseEntity.getStatusCode().toString());
                    response.setErrorcode(HttpServletResponse.SC_UNAUTHORIZED+"");
                    response.setValue("获取授权码失败");
                }
            }
        //账户验证错误
        }catch (UsernameNotFoundException e){
            response.setErrorcode(HttpServletResponse.SC_BAD_REQUEST+"");
            response.setValue(e.getMessage());
        }

        return ResponseEntity.status(200).body(response);
    }
}
